package com.jdbc.lesson04;

import com.jdbc.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestTransaction2 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            conn =  JdbcUtils.getConnection();
            //关闭数据库自动提交功能,且自动开启事务
            conn.setAutoCommit(false);
            String sql1 = "update `account` set money = money - 100 where `name` = 'A'";
            st =  conn.prepareStatement(sql1);
            st.executeUpdate();

            int x = 1/0;  //报错

            String sql2 = "update `account` set money = money + 100 where `name` = 'B'";
            st =  conn.prepareStatement(sql2);
            st.executeUpdate();
            //业务完毕，提交事务
            conn.commit();
            System.out.println("事务提交成功");
        } catch (SQLException e) {
            try {
                //如果失败，则默认回滚
                conn.rollback();//如果失败则回滚事务
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}
